import Card from '@/components/Card';
import HealthReport from '@/components/HealthReport';
import { ProForm, ProFormDatePicker, ProFormInstance } from '@/components/Pro/';
import { reportControllerGetConfig as getReportConfig } from '@/services/ess/diagnosisReport';
import { currentControllerGetMaxCurrentData } from '@/services/ess/healthCurrent';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Flex, Popover, Spin, Tabs } from 'antd';
import cls from 'classnames';
import dayjs from 'dayjs';
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import DetailItems from './components/ItemList';
import normalStyles from './index.less';

const cardStyle = {
  marginBottom: 20,
  marginTop: 20,
};

const TYPE = 1; // 电池报告

interface DataItem {
  key?: string;
  label?: string;
}

const Index: React.FC = () => {
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  const { initialState } = useModel('@@initialState');
  const [pageData, setPageData] = useState({
    arrXtest: [],
    data1: [],
    dataAverage: [],
    linPoint: [],
  });
  const [date, setDate] = useState(moment().subtract(1, 'day'));
  const [isEmpty, setEmpty] = useState(true);
  const chartRef = useRef();

  const [tabitmes, setTabitmes] = useState<DataItem[]>([]);
  const [activeKey, setActiveKey] = useState('');
  const [activeName, setActiveName] = useState('');
  const [yuValue, setyuValue] = useState('');
  const formRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(true);
  const [searchTime, setSearchTime] = useState('');
  let maxHeapCount = 0; // 然后，找出最大堆数量

  const submitForm = () => {
    formRef?.current?.submit();
  };

  useEffect(() => {
    getReportConfig({
      stationId: initialState.stationId,
      type: TYPE,
    }).then((res) => {
      if (res.data) {
        setyuValue(res.data.curThreshold);
      }
    });
    submitForm();
    chartRef?.current?.getEchartsInstance()?.resize();
  }, []);

  const onChange = (key: string) => {
    setActiveKey(key);
    setActiveName(tabitmes.find((res) => res.key === key)?.label);
  };

  const initEmpty = () => {
    maxHeapCount = 0;
    setPageData({
      arrXtest: [],
      linPoint: [],
      dataAverage: [],
      data1: [],
    });
    setTabitmes([]);
    setActiveKey('');
    setActiveName('');
    setEmpty(true);
  };

  return (
    <>
      <Card bodyStyle={{ paddingTop: 15, paddingBottom: 15 }}>
        <Flex justify="space-between" align="center">
          <ProForm
            layout="inline"
            formRef={formRef}
            onFinish={async (value) => {
              setSearchTime(value.date + ' ' + moment().format('HH:mm:ss'));
              setDate(value.date);
              setLoading(true);
              let maxResult = await currentControllerGetMaxCurrentData({
                ...value,
                stationId: initialState?.stationId,
              });
              if (maxResult.data === null) {
                chartRef?.current?.getEchartsInstance()?.clear();
                initEmpty();
              } else {
                chartRef?.current?.getEchartsInstance()?.clear();
                let result = maxResult.data;
                if (result.currentDiffData && result.currentDiffData.length) {
                  // let arr = result.currentDiffData.map(res=>{
                  //   let end = res.deviceName.indexOf("堆");
                  //   if(end!==-1){
                  //     return res.deviceName.substring(0,end)
                  //   }
                  // })
                  // let maxCount = 0;
                  // console.log(arr,"充",maxCount,maxHeapCount)

                  let Average = result?.average;
                  let dataAverage = (result.currentDiffData || []).map(() => result.average);
                  if (dataAverage.length === 1) {
                    dataAverage.push(dataAverage[0]);
                  }

                  let items = (result.currentDiffData || [])
                    .filter((res) => {
                      return res.maxCurrentDiff > result.average;
                    })
                    .map((res) => {
                      return {
                        key: res.code,
                        label: res.deviceName,
                      };
                    });
                  // console.log(items, '相关');
                  if (items.length) {
                    setTabitmes(items);
                    setActiveKey(items[0]['key']);
                    setActiveName(items[0]['label']);
                  } else {
                    setTabitmes([]);
                    setActiveKey('');
                    setActiveName('');
                  }

                  let arrXtest = (result.currentDiffData || []).map((res) => res.deviceName);
                  if (arrXtest.length === 1) {
                    arrXtest.push(arrXtest[0]);
                  }

                  let data1 = (result.currentDiffData || []).map((res) => res.maxCurrentDiff);
                  if (data1.length === 1) {
                    data1.push(data1[0]);
                  }
                  let linPoint = data1
                    .map((value, index) => {
                      if (value > Average) {
                        return {
                          name: index,
                          value: `${arrXtest[index]}`,
                          coord: [`${arrXtest[index]}`, value],
                        };
                      }
                      return null;
                    })
                    .filter((res) => res);

                  // console.log(linPoint, '我看下那个');

                  setEmpty(false);

                  setPageData({
                    arrXtest: arrXtest,
                    linPoint: linPoint,
                    dataAverage: dataAverage,
                    data1: data1,
                  });
                } else {
                  initEmpty();
                }
              }

              setLoading(false);
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({ id: 'batteryVoltage.vol.search' }),
              },
              resetButtonProps: false,
            }}
          >
            <ProFormDatePicker
              width={260}
              name="date"
              label={intl.formatMessage({ id: 'batteryVoltage.vol.voltageDate' })}
              initialValue={moment().subtract(1, 'day')}
              fieldProps={{
                disabledDate: (current) => {
                  return current && current >= dayjs().endOf('day');
                },
                allowClear: false,
              }}
            />
          </ProForm>
          <HealthReport date={searchTime} />
        </Flex>
      </Card>
      <Spin tip="加载中..." spinning={loading}>
        <Card
          title={<span>1.{intl.formatMessage({ id: 'batteryVoltage.cluster.stackCurve' })}</span>}
          extra={
            <div>
              <Popover
                placement="bottomRight"
                title={false}
                content={
                  <div className={cls(normalStyles.standardDesc, normalStyles.ruleDesc)}>
                    <h3>{intl.formatMessage({ id: 'batteryVoltage.tips.cluOne' })}:</h3>
                    <ul>
                      <li key="1">{intl.formatMessage({ id: 'batteryVoltage.tips.cluTwo' })}</li>
                      <li key="2">{intl.formatMessage({ id: 'batteryVoltage.tips.cluThree' })}</li>
                      <li key="3">
                        {intl.formatMessage({ id: 'batteryVoltage.tips.cluFour' })}
                        {yuValue}
                        {intl.formatMessage({ id: 'batteryVoltage.tips.cluFive' })}
                      </li>
                    </ul>
                    <div>{intl.formatMessage({ id: 'batteryVoltage.tips.four' })}</div>
                    <Flex justify="space-between">
                      <table>
                        <tbody>
                          <tr>
                            <td>{intl.formatMessage({ id: 'batteryVoltage.tips.four' })}</td>
                            <td>{intl.formatMessage({ id: 'batteryVoltage.tips.cluSix' })}</td>
                          </tr>
                          <tr>
                            <td>{intl.formatMessage({ id: 'batteryVoltage.tips.cluSeven' })}</td>
                            <td>
                              {intl.formatMessage({ id: 'batteryVoltage.tips.cluEight' })}
                              {yuValue}%
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </Flex>
                  </div>
                }
                arrow={true}
              >
                <a href="#">
                  <QuestionCircleOutlined />
                  &nbsp;{intl.formatMessage({ id: 'batteryVoltage.vol.standard' })}
                </a>
              </Popover>
            </div>
          }
          style={cardStyle}
        >
          <div style={{ marginTop: '20px' }}>
            <ReactEcharts
              ref={chartRef}
              option={{
                tooltip: {
                  trigger: 'axis',
                  formatter: function (params) {
                    if (!isEmpty) {
                      const elecData = params?.filter((res) => res.seriesName === '电流差');
                      if (elecData && elecData.length) {
                        return `
                        <div style="background-color: #fff; padding: 10px;">
                          <div>${params[0]['marker']}<span>${elecData[0]['axisValue']}</span></div>
                          <div><span style="font-weight: bold;">${intl.formatMessage({
                            id: 'batteryVoltage.tips.cluEle',
                          })}:</span> ${elecData[0]['value']}A</div>
                        </div>
                      `;
                      }
                    }
                  },
                },
                legend: {
                  data: isEmpty
                    ? []
                    : [
                        intl.formatMessage({ id: 'batteryVoltage.tips.cluNight' }),
                        intl.formatMessage({ id: 'batteryVoltage.tips.cluTen' }),
                      ],
                  right: '0',
                },
                grid: {
                  left: '50px',
                  right: isEnglish ? '90px' : '50px',
                  bottom: '3%',
                  containLabel: true,
                },
                xAxis: {
                  type: 'category',
                  name: '箱',
                  nameTextStyle: {
                    //x轴单位颜色
                    color: '#222',
                  },
                  color: '#222222',
                  boundaryGap: false,
                  data: pageData.arrXtest ?? [],
                  axisLine: {
                    lineStyle: {
                      color: '#e0e0e0',
                    },
                  },
                  axisLabel: {
                    color: '#222222',
                    formatter: function (value) {
                      let maches = value.match(/箱(\d+)堆/);
                      if (maches) {
                        return maches[1];
                      }
                      // return value.substring(1, value.indexOf('堆'));
                    },
                    interval: maxHeapCount - 1 >= 1 ? maxHeapCount - 1 : null,
                  },
                  axisTick: {
                    show: true,
                    inside: true,
                    lineStyle: {
                      color: '#e0e0e0',
                    },
                  },
                },
                yAxis: {
                  type: 'value',
                  name: 'A',
                  nameTextStyle: {
                    //x轴单位颜色
                    color: '#222',
                  },
                  axisLine: {
                    show: true,
                    lineStyle: {
                      color: '#e0e0e0',
                    },
                  },
                  axisLabel: {
                    color: '#222222',
                  },
                  axisTick: {
                    show: true,
                    inside: true,
                    lineStyle: {
                      color: '#e0e0e0',
                    },
                  },
                },
                dataZoom: [
                  {
                    type: 'inside',
                  },
                ],
                series: [
                  {
                    name: '电流差',
                    type: 'line',
                    data: pageData.data1 ?? [],
                    itemStyle: {
                      color: '#67C23A',
                    },
                    lineStyle: {
                      width: 4,
                    },
                    markPoint: {
                      data: pageData.linPoint ?? [],
                      symbolSize: 70,
                      label: {
                        show: true,
                      },
                    },
                  },
                  {
                    name: '电流差平均值',
                    type: 'line',
                    data: pageData.dataAverage ?? [],
                    symbol: 'circle', // 修改数据点形状为圆形
                    label: {
                      show: pageData.dataAverage?.[0] === 0 ? true : false,
                      formatter: intl.formatMessage({ id: 'batteryVoltage.tips.cluSevth' }),
                    },
                    lineStyle: {
                      width: 4,
                    },
                    endLabel: {
                      show: pageData.dataAverage?.[0] === 0 ? false : true,
                    },
                    itemStyle: {
                      color: '#1A6CFE',
                    },
                  },
                ],
                graphic: [
                  {
                    type: 'image',
                    silent: true,
                    style: {
                      image: require('@/assets/img/empty.png'),
                      width: 180,
                      height: 120,
                    },
                    bounding: 'raw',
                    top: 'center',
                    left: 'center',
                    invisible: !isEmpty,
                  },
                  {
                    type: 'text', // 类型：文本
                    left: 'center',
                    top: '65%',
                    silent: true, // 不响应事件
                    invisible: !isEmpty, // 有数据就隐藏
                    style: {
                      fill: '#222',
                      text: intl.formatMessage({ id: 'global.noDataYet' }),
                      fontFamily: 'Microsoft YaHei',
                      fontSize: '14px',
                    },
                  },
                ],
              }}
            ></ReactEcharts>
            <p className={normalStyles.chars_desc}>
              {intl.formatMessage({ id: 'batteryVoltage.tips.cluTwe' })}
              {tabitmes.length}){intl.formatMessage({ id: 'batteryVoltage.tips.cluTweAfter' })}
            </p>
          </div>
        </Card>
        <Card
          title={<span>2.{intl.formatMessage({ id: 'batteryVoltage.cluster.clusterCurve' })}</span>}
        >
          <Tabs
            activeKey={activeKey}
            items={tabitmes}
            className={cls('global-tabs')}
            onChange={onChange}
            style={{ paddingBottom: 0 }}
          />
          <DetailItems
            activeKey={activeKey}
            activeName={activeName}
            date={date}
            yuValue={yuValue}
          />
          ,
        </Card>
      </Spin>
    </>
  );
};

export default Index;
